const { writeFileSync, needParam } = require("../../utils");
const { getAddEditStr } = require("./add-edit");
const { getBaseCrudStr } = require("./crud");
const { getFormStr } = require("./form");
const { getTableStr } = require("./table");

module.exports = {
  /**
   * 生成增删改查模块
   * @param {string} pathStr 要写入的路径，例："/demo/test"
   * @param {object} options 配置信息
   */
  crateCrudModule(pathStr = needParam(), options = needParam()) {
    const { queryFields, tableCols, addEditFields } = options;
    if (!queryFields) throw new Error(`请传入 queryFields 配置`);
    if (!tableCols) throw new Error(`请传入 tableCols 参数`);
    if (!addEditFields) throw new Error(`请传入 addEditFields 配置`);
    writeFileSync(`${pathStr}/index.vue`, getBaseCrudStr(queryFields, tableCols));
    writeFileSync(`${pathStr}/AddEdit.vue`, getAddEditStr(addEditFields));
  },
  // 生成表格文件
  createFormFile(pathStr = needParam(), fields = needParam()) {
    writeFileSync(pathStr, getFormStr(fields));
  },
  // 生成表单文件
  createTableFile(pathStr = needParam(), cols = [], rows = []) {
    writeFileSync(pathStr, getTableStr(cols, rows));
  },
  // 根据菜单生成模块，basePathStr：/demo/menus
  createModulesByMenus(basePathStr = needParam(), menus = needParam(), options = needParam()) {
    function cycle(list = []) {
      if (!list.length) return;
      list.forEach(item => {
        const { type, link_type, label, path, children, component } = item;
        const isMenu = type === 0;
        const isPage = type === 1 && link_type == 0;
        const isDetail = type == 2;
        if (isMenu) return cycle(children);
        if (isPage) {
          const pathUrl = component.slice(0, component.lastIndexOf("/"));
          return module.exports.crateCrudModule(`${basePathStr}${pathUrl}`, options);
        }
        if (isDetail) {
          module.exports.createFormFile(`${basePathStr}${component}`, options.addEditFields);
        }
      });
    }
    cycle(menus);
  },
};
